package com.example.cathouse;

import android.content.Context;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import java.util.List;

public class CatRepository {
    private LiveData<List<Cat>> allCatsLive;
    private CatDao catDao;

    public CatRepository(Context context) {
        CatDatabase catDatabase = CatDatabase.getDatabase(context.getApplicationContext());
        catDao = catDatabase.getCatDao();
        allCatsLive = catDao.getAllCatsLive();
    }

    void insertCats(Cat... cats) {
        new InsertAsyncTask(catDao).execute(cats);
    }

    void updateCats(Cat... cats) {
        new UpdateAsyncTask(catDao).execute(cats);
    }

    void deleteCats(Cat... cats) {
        new DeleteAsyncTask(catDao).execute(cats);
    }

    void deleteAllCats() {
        new DeleteAllAsyncTask(catDao).execute();
    }

    LiveData<Cat> getCat(int id) {
        return catDao.getCat(id);
    }

    public LiveData<List<Cat>> getAllCatsLive() {
        return allCatsLive;
    }

    public LiveData<List<Cat>> findCatWithPattern(String pattern) {
        return catDao.findCatsWithPattern("%" + pattern + "%");     //模糊匹配
    }

    class InsertAsyncTask extends AsyncTask<Cat, Void, Void> {
        private CatDao catDao;

        public InsertAsyncTask(CatDao catDao) {
            this.catDao = catDao;
        }

        @Override
        protected Void doInBackground(Cat... cats) {
            catDao.insertCats(cats);
            return null;
        }
    }

    class UpdateAsyncTask extends AsyncTask<Cat, Void, Void> {
        private CatDao catDao;

        public UpdateAsyncTask(CatDao catDao) {
            this.catDao = catDao;
        }

        @Override
        protected Void doInBackground(Cat... cats) {
            catDao.updateCats(cats);
            return null;
        }
    }

    class DeleteAsyncTask extends AsyncTask<Cat, Void, Void> {
        private CatDao catDao;

        public DeleteAsyncTask(CatDao catDao) {
            this.catDao = catDao;
        }

        @Override
        protected Void doInBackground(Cat... cats) {
            catDao.deleteCats(cats);
            return null;
        }
    }

    class DeleteAllAsyncTask extends AsyncTask<Void, Void, Void> {
        private CatDao catDao;

        public DeleteAllAsyncTask(CatDao catDao) {
            this.catDao = catDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            catDao.deleteAllCats();
            return null;
        }
    }

}





